//
//  BookReadingViewController.m
//  HelpThePoor
//
//  Created by van7ish on 2016/12/19.
//  Copyright © 2016年 van7ish. All rights reserved.
//

#import "BookReadingViewController.h"
#import "HZRScrollView.h"
#import "ZRImageScrollView.h"
#import "BookPreviewVC.h"
#import "UIButton+WebCache.h"
#import "HTThumbnailView.h"
#import "HTThumbnailCell.h"

@interface BookReadingViewController () <HZRScrollViewDataSource, HZRScrollViewTypeDelegate,HTThumbnailViewDelegate>

/** 数据源 */
@property (nonatomic, strong) NSMutableArray * dataArr;
/** 滚动视图 */
@property (nonatomic, strong) HZRScrollView * scrollView;
/** 点击手势呼出菜单 */
@property (nonatomic, strong) UITapGestureRecognizer * tapGesture;
/** 页码 */
@property (nonatomic, strong) UILabel * pageLabel;
/** 菜单头视图 */
@property (nonatomic, strong) UIView * menuHeader;
/** 菜单脚视图 */
@property (nonatomic, strong) UIView * menuFooter;

@property (nonatomic, strong) UIButton *markBtn;

@property (nonatomic, assign) NSInteger     pageIndex;

@property (nonatomic, strong) UIProgressView    *progressV;
@property (nonatomic, strong) UILabel           *progressLabel;

@property (nonatomic, assign) BOOL      isback;


@end

@implementation BookReadingViewController

#pragma mark - lazy load

- (UITapGestureRecognizer *)tapGesture{
    if (!_tapGesture) {
        _tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showMenu)];
    }
    return _tapGesture;
}

-(UIProgressView*)progressV{
    if (!_progressV) {
        _progressV = [[UIProgressView alloc] initWithFrame:CGRectMake(10, SCREEN_H-7, SCREEN_W-10-70, 4)];
        _progressV.backgroundColor = [UIColor clearColor];
        _progressV.progressTintColor = [UIColor greenColor];
        _progressV.trackTintColor = [UIColor lightGrayColor];
        _progressV.progressViewStyle = UIProgressViewStyleDefault;
    }
    return _progressV;
}

-(UILabel*)progressLabel{
    if (!_progressLabel) {
        _progressLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_W-63, SCREEN_H-12, 60, 10)];
        _progressLabel.backgroundColor = [UIColor clearColor];
        _progressLabel.font = [UIFont systemFontOfSize:9];
        _progressLabel.textColor = [UIColor blackColor];
        
    }
    return _progressLabel;
}

- (UIView *)menuHeader{
    if (!_menuHeader) {
        _menuHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 49)];
        _menuHeader.backgroundColor = COLOR_BOOKDETAILBGCOLOR;
        _menuHeader.userInteractionEnabled = YES;
        
        UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(3, 5, 44, 44)];
        [backButton setImage:ImageNamed(@"back") forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        [backButton initWithBlock:^(id obj) {
            DLog(@"返回");
            weakSelf.isback = YES;
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        } for:UIControlEventTouchUpInside];
        [_menuHeader addSubview:backButton];
        
        
        _markBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W-30, 15, 24, 24)];
        [_markBtn setBackgroundImage:ImageNamed(@"添加书签") forState:UIControlStateNormal];
        [_markBtn initWithBlock:^(id obj) {
            DLog(@"书签");
            NSString *key = nil;
            if (weakSelf.isMagazine) {
                key = [NSString stringWithFormat:@"%@_%@_%@",weakSelf.dataDic[@"issuename"],weakSelf.dataDic[@"issueid"],@(weakSelf.pageIndex)];
            }
            else{
                key = [NSString stringWithFormat:@"%@_%@_%@",weakSelf.dataDic[@"name"],weakSelf.dataDic[@"id"],@(weakSelf.pageIndex)];
            }

            NSString *str = [Tool getValueFromKey:key];
            if (str&&[str length] > 0) {
                [Tool removeKeyValue:key];
                [weakSelf.markBtn setBackgroundImage:ImageNamed(@"添加书签") forState:UIControlStateNormal];
                [SVProgressHUD showInfoWithStatus:@"删除成功"];
                [SVProgressHUD dismissWithDelay:1.5];
            }
            else{
                [Tool setValueForKey:@"1" key:key];
                [SVProgressHUD showInfoWithStatus:@"添加成功"];
                [SVProgressHUD dismissWithDelay:1.5];
                [weakSelf.markBtn setBackgroundImage:ImageNamed(@"选择书签") forState:UIControlStateNormal];
            }
            
        } for:UIControlEventTouchUpInside];
        [_menuHeader addSubview:_markBtn];

        UIButton *marklistBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W-65, 15, 24, 24)];
        [marklistBtn setBackgroundImage:ImageNamed(@"书签图片列表") forState:UIControlStateNormal];
        [marklistBtn addTarget:self action:@selector(lookList:) forControlEvents:UIControlEventTouchUpInside];
        [_menuHeader addSubview:marklistBtn];
        
    }
    return _menuHeader;
}

-(UIView *)menuFooter{
    if (!_menuFooter) {
        
        _menuFooter = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_H - 120, SCREEN_W, 120)];
        _menuFooter.backgroundColor = [UIColor whiteColor];
        _menuFooter.userInteractionEnabled = YES;
        
        UIScrollView *scv = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 120)];
        scv.tag = 11;
        NSInteger count = 0;
        if (self.native) {
            //有多少张图片就显示多少页
            count = [self.dataArr count];
        } else {
            count = self.pages;
        }

        HTThumbnailView *bv = [[HTThumbnailView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 120)];
        bv.tag = 11;
        bv.delegate = self;
        bv.native = self.native;
        bv.dataArr = self.dataArr;
        bv.filePath = self.filePath;
        bv.pages = count;
        [_menuFooter addSubview:bv];
        [bv reloadView];
        
//        for (int i = 0; i < count; i++) {
//            UIButton *ima = [[UIButton alloc] initWithFrame:CGRectMake(5+i*(15+60), 5, 60, 80)];
//            if (self.native) {
//                [ima setImage:[UIImage imageWithContentsOfFile:[self.filePath stringByAppendingPathComponent:self.dataArr[i]]] forState:UIControlStateNormal];
//            } else {
//                [ima sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@/%ld.jpg", KHostAddress, self.filePath, (long)(i + 1)]] forState:UIControlStateNormal placeholderImage:ImageNamed(@"placeholdershuji")];
//            }
//            ima.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
//
//            [[ima imageView] setContentMode:UIViewContentModeScaleAspectFill];
//
//
//            ima.contentHorizontalAlignment= UIControlContentHorizontalAlignmentFill;
////
//            ima.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
//            ima.tag = 100+i;
//            [ima addTarget:self action:@selector(gotoNextPage:) forControlEvents:UIControlEventTouchUpInside];
//            [scv addSubview:ima];
//            ima.layer.borderColor = RGBA_COLOR(235, 235, 235, 1).CGColor;
//            ima.layer.borderWidth =1;
//
//            if (i == 0) {
//                ima.width = 60;
//                ima.height = 80;
//                ima.top = 0;
//                ima.layer.borderColor = [UIColor greenColor].CGColor;
//                ima.layer.borderWidth = 1;
//            }
//
//            UILabel *numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, ima.bottom+5, 60*SCREEN_W/SCREEN_H, 10)];
////            numberLabel.backgroundColor = [UIColor redColor];
//            numberLabel.font = [UIFont systemFontOfSize:9];
//            numberLabel.textAlignment = NSTextAlignmentCenter;
//            numberLabel.textColor = [UIColor blackColor];
//            numberLabel.text = [NSString stringWithFormat:@"%d",i+1];
//            [ima addSubview:numberLabel];
//        }
//        scv.contentSize = CGSizeMake(count*(15+7+60), 120);
//        [_menuFooter addSubview:scv];
    
    }
    return _menuFooter;
}

- (HZRScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[HZRScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-120)];
        _scrollView.dataSource = self;
        _scrollView.typeDelegate = self;
        [_scrollView addGestureRecognizer:self.tapGesture];
    }
    return _scrollView;
}

#pragma mark - lify Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = COLOR_WHITE;
    _pageIndex = 0;
    _isback = NO;
    [self readDataSource];
//
    [self.view addSubview:self.scrollView];
//
    [self.view addSubview:self.menuHeader];
    [self.view addSubview:self.menuFooter];
    [self.view addSubview:self.progressV];
    [self.view addSubview:self.progressLabel];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bateryLevelChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//-(void)viewWillAppear:(BOOL)animated{
//    [self.scrollView gotoPage:4];
//}

- (void)dealloc{
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceBatteryLevelDidChangeNotification object:nil];
    
    DLog(@"%s", __func__);
}

#pragma mark - 读取数据
-(void)readDataSource{
    if (self.dataArr) {
        [self.dataArr removeAllObjects];
    }else{
        self.dataArr = [[NSMutableArray alloc] init];
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *tempFileList = [[NSArray alloc] initWithArray:[fileManager contentsOfDirectoryAtPath:self.filePath error:nil]];
    
    //取出图片名
    for (NSString * str in tempFileList) {
        //存到数据源中
        if (([str hasSuffix:@"png"] || [str hasSuffix:@"jpg"]) && str.length == 5) {
            //1.jpg 2.jpg...9.jpg
            [self.dataArr addObject:str];
        }
    }
    
    for (NSString * str in tempFileList) {
        //存到数据源中
        if (([str hasSuffix:@"png"] || [str hasSuffix:@"jpg"]) && str.length == 6) {
            //10.jpg 20.jpg...99.jpg
            [self.dataArr addObject:str];
        }
    }
    
    for (NSString * str in tempFileList) {
        //存到数据源中
        if (([str hasSuffix:@"png"] || [str hasSuffix:@"jpg"]) && str.length == 7) {
            //100.jpg 200.jpg...9999.jpg
            [self.dataArr addObject:str];
        }
    }
}

#pragma HZRScrollViewTypeDelegate Method
//给ScrollView返回子视图
-(UIView *)subViewType:(NSInteger)atIndex{
    ZRImageScrollView *scrollView = [[ZRImageScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-120)];
    return scrollView;
}

#pragma mark -  HZRScrollViewDataSource Methods
-(void)loadTwoPage{
    _pageIndex = 1;
    NSString *key = nil;
    if (_isMagazine) {
        key = [NSString stringWithFormat:@"%@_%@_%@",self.dataDic[@"issuename"],self.dataDic[@"issueid"],@(_pageIndex)];
    }
    else{
        key = [NSString stringWithFormat:@"%@_%@_%@",self.dataDic[@"name"],self.dataDic[@"id"],@(_pageIndex)];
    }
    
    NSString *str = [Tool getValueFromKey:key];
    if (str&&[str length] > 0) {
        [_markBtn setBackgroundImage:ImageNamed(@"选择书签") forState:UIControlStateNormal];
    }
    else{
        [_markBtn setBackgroundImage:ImageNamed(@"添加书签") forState:UIControlStateNormal];
    }
    
    HTThumbnailView *scv = [_menuFooter viewWithTag:11];
    scv.selectIndex = _pageIndex;
    for (HTThumbnailCell *sv in scv.m_collectionView.subviews) {
        NSLog(@"%@",sv);
        NSInteger tag = sv.index;
        if (tag == _pageIndex) {
            sv.layer.borderColor = [UIColor greenColor].CGColor;
            sv.layer.borderWidth = 1;
            [self.progressV setProgress:((float)(_pageIndex+1)/_pages)];
            [self.progressLabel setText:[NSString stringWithFormat:@"%.2f%%",((float)(_pageIndex+1)/_pages)*100]];
        }
        else{
            sv.layer.borderColor = [UIColor clearColor].CGColor;
        }
    }
    
}

-(void)loaddaoTwoPage:(NSInteger)page{
    _pageIndex = page;
    NSString *key = nil;
    if (_isMagazine) {
        key = [NSString stringWithFormat:@"%@_%@_%@",self.dataDic[@"issuename"],self.dataDic[@"issueid"],@(_pageIndex)];
    }
    else{
        key = [NSString stringWithFormat:@"%@_%@_%@",self.dataDic[@"name"],self.dataDic[@"id"],@(_pageIndex)];
    }
    
    NSString *str = [Tool getValueFromKey:key];
    if (str&&[str length] > 0) {
        [_markBtn setBackgroundImage:ImageNamed(@"选择书签") forState:UIControlStateNormal];
    }
    else{
        [_markBtn setBackgroundImage:ImageNamed(@"添加书签") forState:UIControlStateNormal];
    }
    
    HTThumbnailView *scv = [_menuFooter viewWithTag:11];
    scv.selectIndex = _pageIndex;
    for (HTThumbnailCell *sv in scv.m_collectionView.subviews) {
        NSLog(@"%@",sv);
        NSInteger tag = sv.index;
        if (tag == _pageIndex) {
            sv.layer.borderColor = [UIColor greenColor].CGColor;
            sv.layer.borderWidth = 1;
            [self.progressV setProgress:((float)(_pageIndex+1)/_pages)];
            [self.progressLabel setText:[NSString stringWithFormat:@"%.2f%%",((float)(_pageIndex+1)/_pages)*100]];
        }
        else{
            sv.layer.borderColor = [UIColor clearColor].CGColor;
        }
    }
}

//告诉ScrollView总共要显示多少页
-(NSInteger)numberOfPages{
    
    if (self.native) {
        //有多少张图片就显示多少页
        return [self.dataArr count];
    } else {
        return self.pages;
    }
    
}

-(void)loadComplete{
    if (self.isback) {
        return;
    }
    NSInteger page = 0;
    if (_isMagazine) {
        if ([Tool getValueFromKey:[self.dataDic[@"issueid"] stringValue]]) {
            page = [[Tool getValueFromKey:[self.dataDic[@"issueid"] stringValue]] integerValue];
            [self.scrollView gotoPage:page];
        }
        
    }
    else{
        if ([Tool getValueFromKey:[self.dataDic[@"id"] stringValue]]) {
            page = [[Tool getValueFromKey:[self.dataDic[@"id"] stringValue]] integerValue];
            [self.scrollView gotoPage:page];
        }
    }
    
    [self.progressV setProgress:((float)(page+1)/_pages)];
    [self.progressLabel setText:[NSString stringWithFormat:@"%.2f%%",((float)(page+1)/_pages)*100]];
    
}

//刷新显示内容
-(void)refreshSubView:(UIView *)view atIndex:(NSInteger)index{
    DLog(@"index = %ld", index);
    _pageIndex = _scrollView.currentPage;
    NSString *key = nil;
    if (_isMagazine) {
        key = [NSString stringWithFormat:@"%@_%@_%@",self.dataDic[@"issuename"],self.dataDic[@"issueid"],@(_pageIndex)];
    }
    else{
        key = [NSString stringWithFormat:@"%@_%@_%@",self.dataDic[@"name"],self.dataDic[@"id"],@(_pageIndex)];
    }

    if (_pageIndex == index) {
        HTThumbnailView *scv = [_menuFooter viewWithTag:11];
        scv.selectIndex = _pageIndex;
        if (_pageIndex != 0) {
            if (_isMagazine) {
                [Tool setValueForKey:@(_pageIndex) key:[self.dataDic[@"issueid"] stringValue]];
                if (_pageIndex==0||_pageIndex==1||_pageIndex==2) {
                    [scv.m_collectionView setContentOffset:CGPointMake(0, 0)];
                }else{
                    [scv.m_collectionView setContentOffset:CGPointMake(-(SCREEN_W/2-30)+70*_pageIndex, 0)];
                }
            }
            else{
                [Tool setValueForKey:@(_pageIndex) key:[self.dataDic[@"id"] stringValue]];
                if (_pageIndex==0||_pageIndex==1||_pageIndex==2) {
                    [scv.m_collectionView setContentOffset:CGPointMake(0, 0)];
                }else{
                    [scv.m_collectionView setContentOffset:CGPointMake(-(SCREEN_W/2-30)+70*_pageIndex, 0)];
                }
            }
        }

        
        for (HTThumbnailCell *sv in scv.m_collectionView.subviews) {
            NSInteger tag = sv.index;
            if (tag == _pageIndex) {
                sv.layer.borderColor = [UIColor greenColor].CGColor;
                sv.layer.borderWidth = 1;
                [self.progressV setProgress:((float)(_pageIndex+1)/_pages)];
                [self.progressLabel setText:[NSString stringWithFormat:@"%.2f%%",((float)(_pageIndex+1)/_pages)*100]];
                if (_pageIndex==0||_pageIndex==1||_pageIndex==2) {
                    [scv.m_collectionView setContentOffset:CGPointMake(0, 0)];
                }else{
                   [scv.m_collectionView setContentOffset:CGPointMake(-(SCREEN_W/2-30)+70*_pageIndex, 0)];
                }
            }
            else{
                sv.layer.borderColor = [UIColor clearColor].CGColor;
            }
        }
    }
    
    NSString *str = [Tool getValueFromKey:key];
    if (str&&[str length] > 0) {
        [_markBtn setBackgroundImage:ImageNamed(@"选择书签") forState:UIControlStateNormal];
    }
    else{
        [_markBtn setBackgroundImage:ImageNamed(@"添加书签") forState:UIControlStateNormal];
    }
    self.menuHeader.hidden = YES;
    
    ZRImageScrollView *scrollView = (ZRImageScrollView *)view;
    
//    scrollView.zoomScale = 0.8;
    
    if (self.native) {
        scrollView.imageView.image = [UIImage imageWithContentsOfFile:[self.filePath stringByAppendingPathComponent:self.dataArr[index]]];
    } else {
        [scrollView.imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@/%ld.jpg", KHostAddress, self.filePath, (long)(index + 1)]] placeholderImage:ImageNamed(@"placeholdershuji")];
    }
    [self.tapGesture requireGestureRecognizerToFail:scrollView.doubleTapGesture];
    
    self.pageLabel.text = [NSString stringWithFormat:@"%ld/%ld", index, self.pages];
}

#pragma mark - 事件处理

- (void)hideMenu{
    self.menuHeader.hidden = YES;
    [[UIApplication sharedApplication] setStatusBarHidden:TRUE];
}

- (void)showMenu{
    if (self.menuHeader.hidden) {
        self.menuHeader.hidden = NO;
        [[UIApplication sharedApplication] setStatusBarHidden:FALSE];
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    } else {
        [self hideMenu];
    }
}

- (void)bateryLevelChanged:(NSNotification *)notify{
    DLog(@"%@", notify.object);
    UILabel *bateryLabel = (UILabel *)[self.menuFooter viewWithTag:10];
    bateryLabel.text = [NSString stringWithFormat:@"%.0f%%", [Tool getBatteryQuantity] * 100];
}

#pragma mark - 在本页隐藏状态栏
- (BOOL)prefersStatusBarHidden{
    return YES;
}

-(void)gotoNextPage:(UIButton*)sender{
    __weak typeof(self)weakSelf = self;
    NSInteger tag = sender.tag - 100;
    [weakSelf.scrollView gotoPage:tag];
}

-(void)didselectIndex:(NSInteger)index{
    [self.scrollView gotoPage:index];
}

-(void)lookList:(UIButton*)sender{
    DLog(@"书签列表");
    __weak typeof(self)weakSelf = self;
    BookPreviewVC *pv = [BookPreviewVC new];
    pv.filePath = self.filePath;
    pv.pages = self.pages;
    pv.dataArr  = self.dataArr;
    pv.native = self.native;
    pv.isMagazine = self.isMagazine;
    pv.dataDic = self.dataDic;
    
    pv.gotoMarkpage = ^(int page) {
        [weakSelf.scrollView gotoPage:page];
    };
    [self.navigationController pushViewController:pv animated:NO];
}


@end
